package com.csc.mtlbatch.jde.cls;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.FlatFileItemWriter;

import com.csc.dataaccess.entity.Ljdeexttrt;
import com.csc.mtlbatch.util.ClsResourceUtil;

public class Ct087FileHeaderFooter implements ItemWriter<Ljdeexttrt>,
FlatFileFooterCallback, FlatFileHeaderCallback, ItemStream {
	
	private FlatFileItemWriter<Ljdeexttrt> delegate;
	private int recordCount = 0;

	@Override
	public void close() throws ItemStreamException {
		this.delegate.close();
	}

	@Override
	public void open(ExecutionContext arg0) throws ItemStreamException {
		this.delegate.open(arg0);		
	}

	@Override
	public void update(ExecutionContext arg0) throws ItemStreamException {
		this.delegate.update(arg0);		
	}
	
	public void setDelegate(FlatFileItemWriter<Ljdeexttrt> delegate) {
        this.delegate = delegate;
    }

	@Override
	public void writeHeader(Writer arg0) throws IOException {
		
		String strfileName  = ClsResourceUtil.getFileLocation();
		String strDateStamp  = ClsResourceUtil.getDateStamp();

		arg0.write("HEADER" + "," + strfileName + "," + strDateStamp);
	}

	@Override
	public void writeFooter(Writer arg0) throws IOException {
		recordCount = recordCount + 1;
		arg0.write("FOOTER," + recordCount);
	}

	@Override
	public void write(List<? extends Ljdeexttrt> items) throws Exception {
        int chunkRecord = 0;
        for (Ljdeexttrt ljdeexttrt : items) {
            chunkRecord++;
        }
        delegate.write(items);
        // After successfully writing all items
        recordCount += chunkRecord;
        
	}

}
